package yy.zn.service;

import org.springframework.stereotype.Service;
import yy.zn.commom.Helper;
import yy.zn.entity.*;
import yy.zn.mapper.DataMapper;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author LiuLei
 */
@Service
public class DataServiceImpl implements DataService {

    @Resource
    private DataMapper dataMapper;

    @Override
    public Moco MOCO_LIST(String mocCode) throws Exception {
        if (Helper.isEmpty(mocCode)) throw new Exception("产品编号不能同时为空！");
        MocoRders mocoRders = dataMapper.mocoReders(mocCode);
        if (mocoRders == null) throw new Exception("暂无数据！");
        // 查询所有的物料信息
        List<MocoRdersBordy> mocoRdersBordies = dataMapper.mocoRedersBordyList(Collections.singletonList(mocoRders.getMoDId()));
        return new Moco(mocoRders, mocoRdersBordies);
    }

    @Override
    public Goods GOODS(String barCode) {
        return dataMapper.goods(barCode);
    }

    @Override
    public Map<String, Goods> GOODS_LIS(Set<String> barCode) throws Exception {
        List<Goods> goods = dataMapper.goodsLis(barCode);
        if (goods.isEmpty()) throw new Exception("暂无数据！");
        Map<String, Goods> map = new HashMap<>(goods.size());
        goods.forEach(data -> map.put(data.getWhCode(), data));
        return map;
    }

    @Override
    public List<QueryInfo> RECEIVE_OR_SEND_TYPE(int type) {
        return dataMapper.receiveOrSendType(type);
    }

    @Override
    public List<QueryInfo> PUR_TYPE() {
        return dataMapper.purType();
    }

    @Override
    public List<QueryInfo> SALE_TYPE() {
        return dataMapper.saleType();
    }

    @Override
    public Map<String, SaleOrder> SALE_ORDER(String order) {
        return dataMapper.saleOrder(order);
    }

    @Override
    public int AUDIT_SALE_ORDER(Map<String, Object> map) {
        return dataMapper.auditSaleOrder(map);
    }

    @Override
    public List<Position> POSITION(Map<String, String> param) {
        return dataMapper.position(param).stream().filter(data -> {
            BigDecimal bigDecimal = data.getiQuantity();
            return bigDecimal != null && (bigDecimal.compareTo(BigDecimal.ZERO) > 0);
        }).sorted((a, b) -> {
            int compared = a.getcBatch().compareTo(b.getcBatch());
            if (compared == 0) return a.getiQuantity().compareTo(b.getiQuantity());
            return compared;
        }).collect(Collectors.toList());
    }

    @Override
    public List<Produce> PRODUCE_QTY(String bar) {
        return dataMapper.produceQty(bar);
    }

    @Override
    public List<ProduceInv> PRODUCE_INV(String bar) {
        return dataMapper.produceInv(bar)
                .stream()
                .filter(inv -> inv.getQty().compareTo(inv.getIssQty()) > 0)
                .sorted(Comparator.comparing(ProduceInv::getInvCode))
                .collect(Collectors.toList());
    }

    @Override
    public List<InvCode> GET_INV_BY_INVCODE(String bar) {
        return dataMapper.getInvByInvCode(bar);
    }

    @Override
    public List<InvCode> GET_INV_BY_INVCODE(List<String> bar) {
        return dataMapper.getInvByInvCodes(bar);
    }

//    @Override
//    public ArrivalDl ARRIVAL_VOUCH(String bar) {
//        ArrivalDl dl = new ArrivalDl();
//        List<Arrival> arrivals = dataMapper.arrival(Collections.singletonMap("bar", bar));
//        if (arrivals.isEmpty()) throw new RuntimeException("暂无到货单数据！");
//        Arrival val = arrivals.get(0);
//        // 判断数量是否相等并且判断是否是合并单
//        if (val.getQty().compareTo(val.getiQuantity()) == 0 && val.getParentType() == 0) {
//            // 默认 normal
//            List<ArrivalVouch> vouches = dataMapper.arrivalVouchList(Collections.singletonList(val.getBarCode()));
//            dl.setNormal(vouches.get(0));
//            return dl;
//        }
//        // 非默认单设置 是合并单
//        arrival(val, dl, new HashSet<>());
//        return dl;
//    }

//    @Override
//    public ArrivalVouch ARRIVAL_VOUCH(String bar) {
//        List<ArrivalVouch> arrivals = dataMapper.arrivalVouchLists(Collections.singletonMap("bar", bar));
//        if (arrivals.isEmpty()) throw new RuntimeException("暂无到货单数据！");
//        return arrivals.get(0);
//    }

    @Override
    public ArrivalVouch ARRIVAL_VOUCH(String bar) {
        ArrivalVouch arrivals = dataMapper.arrivalProcesses(bar);
        if (arrivals == null) throw new RuntimeException("暂无到货单数据！");
        return arrivals;
    }

    @Override
    public List<ArrivalVouch> ARRIVAL_VOUCH_LIST(String code) {
        List<ArrivalVouch> arrivals = dataMapper.arrivalVouchLists(Collections.singletonMap("code", code));
        if (arrivals.isEmpty()) throw new RuntimeException("暂无到货单数据！");
        return arrivals;
    }

//    @Override
//    public List<ArrivalDl> ARRIVAL_VOUCH_LIST(String code) {
//        List<ArrivalDl> dlList = new LinkedList<>();
//        List<Arrival> arrivals = dataMapper.arrival(Collections.singletonMap("code", code));
//        if (arrivals.isEmpty()) throw new RuntimeException("暂无到货单数据！");
//        Set<String> hasBar = new HashSet<>();
//        // 获取按照物料编号进行分组的集合
//        Collection<List<Arrival>> valGroupList = arrivals.stream()
//                .collect(Collectors
//                        .groupingBy(data -> data.getcInvCode() + "-" + data.getcBatch())
//                )
//                .values();
//        // 遍历分组
//        for (List<Arrival> arrivalList : valGroupList) {
//            for (Arrival val : arrivalList) {
//                ArrivalDl dl = new ArrivalDl();
//                // 到货单
//                // 判断数量是否相等并且判断是否是合并单
//                if (val.getQty().compareTo(val.getiQuantity()) == 0 && val.getParentType() == 0) {
//                    // 默认 normal
//                    List<ArrivalVouch> vouches = dataMapper.arrivalVouchList(Collections.singletonList(val.getBarCode()));
//                    dl.setNormal(vouches.get(0));
//                    dlList.add(dl);
//                    continue;
//                }
//                // 非默认单设置 是合并单
//                arrival(val, dl, hasBar);
//                dlList.add(dl);
//            }
//        }
//        if (hasBar.isEmpty()) return dlList;
//        return dlList.stream().filter(data -> {
//            ArrivalVouch normal = data.getNormal();
//            if (normal == null) return true;
//            return !hasBar.contains(normal.getBarCode());
//        }).collect(Collectors.toList());
//    }

    /**
     * 到货单查询
     *
     * @param arrival 到货单
     * @param dl      到货单结构
     */
    private void arrival(Arrival arrival, ArrivalDl dl, Set<String> hasBar) {
        Map<String, Object> map = new HashMap<>(3);
        map.put("id", arrival.getRecordId());
        map.put("invCode", arrival.getcInvCode());
        map.put("batch", arrival.getcBatch());
        List<String> barList = dataMapper.arrivalVouchMergeBarList(map);
        List<ArrivalVouch> vouches = dataMapper.arrivalVouchList(barList);
        vouches.forEach(data -> {
            // 合并单
            if (arrival.getBarCode().equals(data.getBarCode())) {
                dl.setMerge(data);
            } else {
                // 合并单子单
                List<ArrivalVouch> subset = dl.getSubset();
                if (subset == null) {
                    subset = new LinkedList<>();
                    dl.setSubset(subset);
                }
                hasBar.add(data.getBarCode());
                subset.add(data);
            }
        });
    }

    @Override
    public List<ArrivalRepository> ARRIVAL_REPOSITORY(ArrivalResDto dto) {
        return dataMapper.arrivalRepository(dto);
    }

    @Override
    public InvStock GET_STOCK_BY_INV_AND_BATCH(String invCode, String batch) {
        return dataMapper.getStockByInvAndBatch(invCode, batch);
    }

    @Override
    public String CURRENT_STOCK_DATE(CurDate curDate) {
        return dataMapper.getCurrentStockDateByCur(curDate);
    }

    @Override
    public List<WareHouse> WAREHOUSE() {
        return dataMapper.getAllWareHouse();
    }

    @Override
    public Integer findCurrentIsExistsByPositionCodeAndName(String code, String name) {
        return dataMapper.findCurrentIsExistsByPositionCodeAndName(code, name);
    }

    /**
     * @since 2025/05/19
     */
    @Override
    public List<Position> INV_STOCK(String code) {
        // 查询现存量
        List<Position> quantityOnHand = dataMapper.findQuantityOnHand(code);
        // 如果为空直接返回空
        if (quantityOnHand.isEmpty()) return quantityOnHand;
        // 不为空获取仓库编码
        List<String> whCodes = quantityOnHand.stream()
                .map(Position::getcWhCode)
                .distinct()
                .collect(Collectors.toList());
        // 存货编码+仓库编码列表查询
        List<Position> stocks = dataMapper.getAllInvStock(code, whCodes);
        // 合并返回
        quantityOnHand.addAll(stocks);
        quantityOnHand.sort(
                Comparator.comparing(Position::getcInvCode)
                        .thenComparing(Position::getcBatch)
        );
        return quantityOnHand;
    }

    @Override
    public JsonPage<Inventory> INVENTORY(InvQuery invQuery) {
        Long count = dataMapper.INVENTORY_COUNT(invQuery);
        if (count > 0) {
            List<Inventory> inventory = dataMapper.INVENTORY(invQuery);
            return JsonPage.builder(
                    invQuery.getPage(),
                    invQuery.getSize(),
                    count.intValue(),
                    inventory
            );
        }
        return JsonPage.builder(
                invQuery.getPage(),
                invQuery.getSize(),
                0,
                Collections.emptyList()
        );
    }
}
